package cn.cmkj.auction.ui;

import android.app.Dialog;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import cn.cmkj.auction.R;
import cn.cmkj.auction.app.BaseActivity;
import cn.cmkj.auction.app.Urls;
import cn.cmkj.auction.data.db.User;
import cn.cmkj.auction.data.http.Address;
import cn.cmkj.auction.data.model.CityModel;
import cn.cmkj.auction.data.model.DistrictModel;
import cn.cmkj.auction.data.model.ProvinceModel;
import cn.cmkj.auction.utils.HttpCallback;
import cn.cmkj.auction.utils.XmlParserHandler;
import cn.cmkj.auction.widget.cascade.OnWheelChangedListener;
import cn.cmkj.auction.widget.cascade.WheelView;
import cn.cmkj.auction.widget.cascade.adapters.ArrayWheelAdapter;

/**
 * Created by cunguoyao on 2017/8/30.
 */
@ContentView(R.layout.activity_user_address_edit)
public class UserAddressEditActivity extends BaseActivity implements View.OnClickListener, OnWheelChangedListener {

    @ViewInject(R.id.title_back)
    private ImageButton back;
    @ViewInject(R.id.title_text)
    private TextView titleText;
    @ViewInject(R.id.address_receive_name)
    private EditText addressName;
    @ViewInject(R.id.address_receive_phone)
    private EditText addressPhone;
    @ViewInject(R.id.address_receive_code)
    private EditText addressCode;
    @ViewInject(R.id.address_receive_area_layout)
    private RelativeLayout addressAreaLayout;
    @ViewInject(R.id.address_receive_area)
    private TextView addressArea;
    @ViewInject(R.id.address_receive_location)
    private EditText addressLocation;
    @ViewInject(R.id.btn_submit)
    private Button submit;

    private Address address;
    private WheelView mViewProvince;
    private WheelView mViewCity;
    private WheelView mViewDistrict;
    private Button mBtnConfirm;
    private Dialog mDialog;
    /**
     * 所有省
     */
    protected String[] mProvinceDatas;
    /**
     * key - 省 value - 市
     */
    protected Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
    /**
     * key - 市 values - 区
     */
    protected Map<String, String[]> mDistrictDatasMap = new HashMap<String, String[]>();

    /**
     * key - 区 values - 邮编
     */
    protected Map<String, String> mZipcodeDatasMap = new HashMap<String, String>();

    /**
     * 当前省的名称
     */
    protected String mCurrentProviceName;
    /**
     * 当前市的名称
     */
    protected String mCurrentCityName;
    /**
     * 当前区的名称
     */
    protected String mCurrentDistrictName ="";

    /**
     * 当前区的邮政编码
     */
    protected String mCurrentZipCode ="";

    /**
     * 解析省市区的XML数据
     */

    protected void initProvinceDatas() {
        List<ProvinceModel> provinceList = null;
        AssetManager asset = getAssets();
        try {
            InputStream input = asset.open("province_data.xml");
            // 创建一个解析xml的工厂对象
            SAXParserFactory spf = SAXParserFactory.newInstance();
            // 解析xml
            SAXParser parser = spf.newSAXParser();
            XmlParserHandler handler = new XmlParserHandler();
            parser.parse(input, handler);
            input.close();
            // 获取解析出来的数据
            provinceList = handler.getDataList();
            //*/ 初始化默认选中的省、市、区
            if (provinceList!= null && !provinceList.isEmpty()) {
                mCurrentProviceName = provinceList.get(0).getName();
                List<CityModel> cityList = provinceList.get(0).getCityList();
                if (cityList!= null && !cityList.isEmpty()) {
                    mCurrentCityName = cityList.get(0).getName();
                    List<DistrictModel> districtList = cityList.get(0).getDistrictList();
                    mCurrentDistrictName = districtList.get(0).getName();
                    mCurrentZipCode = districtList.get(0).getZipcode();
                }
            }
            //*/
            mProvinceDatas = new String[provinceList.size()];
            for (int i=0; i< provinceList.size(); i++) {
                // 遍历所有省的数据
                mProvinceDatas[i] = provinceList.get(i).getName();
                List<CityModel> cityList = provinceList.get(i).getCityList();
                String[] cityNames = new String[cityList.size()];
                for (int j=0; j< cityList.size(); j++) {
                    // 遍历省下面的所有市的数据
                    cityNames[j] = cityList.get(j).getName();
                    List<DistrictModel> districtList = cityList.get(j).getDistrictList();
                    String[] distrinctNameArray = new String[districtList.size()];
                    DistrictModel[] distrinctArray = new DistrictModel[districtList.size()];
                    for (int k=0; k<districtList.size(); k++) {
                        // 遍历市下面所有区/县的数据
                        DistrictModel districtModel = new DistrictModel(districtList.get(k).getName(), districtList.get(k).getZipcode());
                        // 区/县对于的邮编，保存到mZipcodeDatasMap
                        mZipcodeDatasMap.put(districtList.get(k).getName(), districtList.get(k).getZipcode());
                        distrinctArray[k] = districtModel;
                        distrinctNameArray[k] = districtModel.getName();
                    }
                    // 市-区/县的数据，保存到mDistrictDatasMap
                    mDistrictDatasMap.put(cityNames[j], distrinctNameArray);
                }
                // 省-市的数据，保存到mCitisDatasMap
                mCitisDatasMap.put(provinceList.get(i).getName(), cityNames);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        if(getIntent().getSerializableExtra("address") != null)
        address = (Address) getIntent().getSerializableExtra("address");
        back.setOnClickListener(this);
        addressAreaLayout.setOnClickListener(this);
        submit.setOnClickListener(this);
        if(address != null) {
            titleText.setText("编辑地址");
            addressName.setText(address.getName());
            addressPhone.setText(address.getMobile());
            addressCode.setText(address.getZip());
            addressArea.setText(address.getArea());
            addressLocation.setText(address.getAddr());
        }else {
            titleText.setText("添加地址");
        }
        addressPhone.setInputType(EditorInfo.TYPE_CLASS_PHONE);
        addressCode.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.address_receive_area_layout:
                popAreaDialog();
                break;
            case R.id.btn_confirm:
                addressArea.setText(mCurrentProviceName + " " + mCurrentCityName + " " + mCurrentDistrictName);
                if(mDialog != null && mDialog.isShowing()) {
                    mDialog.dismiss();
                }
                break;
            case R.id.btn_submit:
                if(TextUtils.isEmpty(addressName.getText())) {
                    Toast.makeText(UserAddressEditActivity.this, "收件人姓名不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(TextUtils.isEmpty(addressPhone.getText())) {
                    Toast.makeText(UserAddressEditActivity.this, "手机号码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(TextUtils.isEmpty(addressCode.getText())) {
                    Toast.makeText(UserAddressEditActivity.this, "邮政编码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(TextUtils.isEmpty(addressArea.getText())) {
                    Toast.makeText(UserAddressEditActivity.this, "请选择区域", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(TextUtils.isEmpty(addressLocation.getText())) {
                    Toast.makeText(UserAddressEditActivity.this, "请输入详细地址", Toast.LENGTH_SHORT).show();
                    return;
                }
                saveAddress();
                break;
        }
    }

    private void saveAddress() {
        User user = getAccount();
        RequestParams params = new RequestParams(Urls.api);
        params.addParameter("method", Urls.saveAddress);
        params.addParameter("accesstoken", user.getToken());
        params.addParameter("member_id", user.getId());
        if(address != null) {
            params.addParameter("ship_id", address.getId());
            params.addParameter("is_default", address.isDefault() ? "true" : "false");
        }else {
            params.addParameter("is_default", "true");
        }
        params.addParameter("ship_name", addressName.getText().toString());
        params.addParameter("ship_area", addressArea.getText().toString());
        params.addParameter("ship_addr", addressLocation.getText().toString());
        params.addParameter("ship_zip", addressCode.getText().toString());
        params.addParameter("ship_tel", addressPhone.getText().toString());
        params.addParameter("ship_mobile", addressPhone.getText().toString());
        x.http().request(HttpMethod.POST, params, new HttpCallback(this) {
            @Override
            public void success(String s) {
                Toast.makeText(UserAddressEditActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                finished();
            }

            @Override
            public void error(Throwable ex, String msg, boolean isOnCallback) {
                Toast.makeText(UserAddressEditActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void cancel(CancelledException e) {

            }

        });
    }

    private void popAreaDialog() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_city_area, null);
        setUpViews(contentView);
        setUpData();
        setUpListener();
        mDialog = new Dialog(this, R.style.AlertDialogStyle);
        mDialog.setContentView(contentView);
        mDialog.show();
        Window window = mDialog.getWindow();
        window.setGravity(Gravity.BOTTOM); //可设置dialog的位置
        window.getDecorView().setPadding(0, 0, 0, 0); //消除边距

        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;   //设置宽度充满屏幕
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);
    }

    private void setUpViews(View view) {
        mViewProvince = (WheelView) view.findViewById(R.id.id_province);
        mViewCity = (WheelView) view.findViewById(R.id.id_city);
        mViewDistrict = (WheelView) view.findViewById(R.id.id_district);
        mBtnConfirm = (Button) view.findViewById(R.id.btn_confirm);
    }

    private void setUpListener() {
        // 添加change事件
        mViewProvince.addChangingListener(this);
        // 添加change事件
        mViewCity.addChangingListener(this);
        // 添加change事件
        mViewDistrict.addChangingListener(this);
        // 添加onclick事件
        mBtnConfirm.setOnClickListener(this);
    }

    private void setUpData() {
        initProvinceDatas();
        mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(this, mProvinceDatas));
        // 设置可见条目数量
        mViewProvince.setVisibleItems(7);
        mViewCity.setVisibleItems(7);
        mViewDistrict.setVisibleItems(7);
        updateCities();
        updateAreas();
    }

    /**
     * 根据当前的市，更新区WheelView的信息
     */
    private void updateAreas() {
        int pCurrent = mViewCity.getCurrentItem();
        mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
        String[] areas = mDistrictDatasMap.get(mCurrentCityName);

        if (areas == null) {
            areas = new String[] { "" };
        }
        mViewDistrict.setViewAdapter(new ArrayWheelAdapter<String>(this, areas));
        mViewDistrict.setCurrentItem(0);
        mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[0];
        mCurrentZipCode = mZipcodeDatasMap.get(mCurrentDistrictName);
    }

    /**
     * 根据当前的省，更新市WheelView的信息
     */
    private void updateCities() {
        int pCurrent = mViewProvince.getCurrentItem();
        mCurrentProviceName = mProvinceDatas[pCurrent];
        String[] cities = mCitisDatasMap.get(mCurrentProviceName);
        if (cities == null) {
            cities = new String[] { "" };
        }
        mViewCity.setViewAdapter(new ArrayWheelAdapter<String>(this, cities));
        mViewCity.setCurrentItem(0);
        updateAreas();
    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        // TODO Auto-generated method stub
        if (wheel == mViewProvince) {
            updateCities();
        } else if (wheel == mViewCity) {
            updateAreas();
        } else if (wheel == mViewDistrict) {
            mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[newValue];
            mCurrentZipCode = mZipcodeDatasMap.get(mCurrentDistrictName);
        }
    }
}
